<?php

namespace app\admin\controller;

use app\common\model\Goodsclass;
use think\Lang;
use think\Db;
use Qiniu\Auth as Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Course extends AdminControl
{

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/course.lang.php');
    }

    /**
     * 主教程列表
     */
    public function index()
    {
        // 品牌
        $brand_list = model('brand')->getBrandPassedList(array());
        $this->assign('brand_list', $brand_list);
        #七牛云图片域名
        $file_http = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $file_http['value']);

        /* 处理商品分类*/
        $choose_gcid = ($t = intval(input('param.choose_gcid'))) > 0 ? $t : 0;
        $gccache_arr = model('goodsclass')->getGoodsclassCache($choose_gcid, 3);
        $this->assign('gc_json', json_encode($gccache_arr['showclass']));
        $this->assign('gc_choose_json', json_encode($gccache_arr['choose_gcid']));

        $class = new Goodsclass();
        $parent_class_list = $class->getGoodsclassList(['gc_parent_id' => 0]);
        $this->assign('class_list', $parent_class_list);

        /*搜索*/
        $status = input('get.status');
        if (trim($status) > 0 && trim($status) != 0) {
            if ($status == 1) {
                $condition['status'] = $status;
            } else {
                $condition['status'] = 0;
            }
        }
        $search_gc_id1 = input('get.search_gc_id1');
        $search_gc_id2 = input('get.search_gc_id2');
        $search_gc_id3 = input('get.search_gc_id3');
        if(!empty($search_gc_id1)){
            $condition['cat_id1'] = $search_gc_id1;
        }
        if(!empty($search_gc_id2)){
            $condition['cat_id2'] = $search_gc_id2;
        }
        if(!empty($search_gc_id3)){
            $condition['cat_id3'] = $search_gc_id3;
        }

        //分类查询
        // $search_gc_id1 = input('get.search_gc_id1', '');
        // $search_gc_id2 = input('get.search_gc_id2', '');
        // $search_gc_id3 = input('get.search_gc_id3', '');
        // if ($search_gc_id1) {
        //     $where['cat_id1'] = ['eq', $search_gc_id1];
        // }
        // if ($search_gc_id2) {
        //     $where['cat_id2'] = ['eq', $search_gc_id2];
        // }
        // if ($search_gc_id3) {
        //     $where['cat_id3'] = ['eq', $search_gc_id3];
        // }

        $title = input('get.title');
        if (trim($title) != '') {
            $condition['title'] = array('like', '%' . trim($title) . '%');
        }

        $type = input('get.type');
        if ($type > 0 && $type != 0) {
            $condition['type'] = $type;
        }

        if ($choose_gcid > 0) {
            $condition['cat_id' . ($gccache_arr['showclass'][$choose_gcid]['depth'])] = $choose_gcid;
        }

        $brand_id = input('get.b_id');
        if (intval($brand_id) > 0) {
            $condition['brand_id'] = intval($brand_id);
        }


        if (empty($condition)) {
            $course_list = Db::name('course')->where('is_del', '<>', 1)->order('id', 'desc')->select();
        } else {
            
            $course_list = Db::name('course')->where('is_del', '<>', 1)->where($condition)->order('id', 'desc')->select();
           
        }
        $brand = DB::name('brand')->select();

        foreach ($course_list as $k => $v) {
            if ($v['status'] == 1) {
                $course_list[$k]['status'] = '停用';
            } else {
                $course_list[$k]['status'] = '启用';
            }
        }
        $this->assign('brand', $brand);
        $this->assign('course_list', $course_list);
        $this->setAdminCurItem('index');
        return $this->fetch('course_list');
    }

    /**
     * 子教程列表
     */
    public function course_son_list()
    {
        $course_id = input('get.course_id');
        $this->assign('course_id', $course_id);
        /*搜索*/
        $status = input('get.status');
        if (trim($status) > 0 && trim($status) != 0) {
            if ($status == 1) {
                $condition['status'] = $status;
            } else {
                $condition['status'] = 0;
            }
        }
        $title = input('get.title');
        if (trim($title) != '') {
            $condition['title'] = array('like', '%' . trim($title) . '%');
        }

        if (empty($condition)) {
            $course_list = Db::name('course_info')->where('is_del', '<>', 1)->where(['course_id' => $course_id])->order('x_id', 'asc')->select();
        } else {
            $course_list = Db::name('course_info')->where('is_del', '<>', 1)->where(['course_id' => $course_id])->order('x_id', 'asc')->where($condition)->select();
        }

        foreach ($course_list as $k => $v) {
            if ($v['status'] == 1) {
                $course_list[$k]['status'] = '启用';
            } else {
                $course_list[$k]['status'] = '停用';
            }
        }
        $this->assign('course_list', $course_list);
        $this->setAdminCurItem('course_son_list');
        return $this->fetch('course_son_list');
    }


    /**
     * 子教程视频展示
     */
    public function video_list()

    {   #七牛云域名
        $file_http = db('config')->where('code', 'qiniu_http')->find();
        $course_id = input('get.id');
        $course_info = DB::name('course_info')->where(['id' => $course_id])->find();
        // p($course_info);die;
        if (empty($course_info['video'])) {
            $data['code'] = 0;
        } else {
            $url = $file_http['value'] . '/' . $course_info['video'];
            $data['code'] = 1;
            $data['video_list'] = $url;
        }
        $this->assign('data', $data);
        return $this->fetch('video_list');
    }

    /**
     * 主教程添加
     */
    public function course_add()
    {
        // 品牌
        $brand_list = model('brand')->getBrandPassedList(array());
        $this->assign('brand_list', $brand_list);

        $goodsclass_model = model('goodsclass');
        if (!request()->isPost()) {
            #获取品牌
            $brand = DB::name('brand')->select();
            $this->assign('brand', $brand);
            //父类列表，只取到第二级
            $parent_list = $goodsclass_model->getTreeClassList(2);
            $gc_list = array();
            if (is_array($parent_list)) {
                foreach ($parent_list as $k => $v) {
                    $parent_list[$k]['gc_name'] = str_repeat("&nbsp;", $v['deep'] * 2) . $v['gc_name'];
                    if ($v['deep'] == 1)
                        $gc_list[$k] = $v;
                }
            }
            $this->assign('gc_list', $gc_list);
            //类型列表
            $type_model = model('type');
            $type_list = $type_model->getTypeList(array(), '', 'type_id,type_name,class_id,class_name');
            $t_list = array();
            if (is_array($type_list) && !empty($type_list)) {
                foreach ($type_list as $k => $val) {
                    $t_list[$val['class_id']]['type'][$k] = $val;
                    $t_list[$val['class_id']]['name'] = $val['class_name'] == '' ? lang('ds_default') : $val['class_name'];
                }
            }

            ksort($t_list);

            $this->assign('type_list', $t_list);
            $this->assign('gc_parent_id', input('get.gc_parent_id'));
            $this->assign('parent_list', $parent_list);
            $this->setAdminCurItem('course_add');
            return $this->fetch('course_add');
        } else {
            $gc_info3 = db('goodsclass')->where('gc_id', input('post.cat_id2'))->find();
            $gc_info2 = db('goodsclass')->where('gc_id', input('post.cat_id1'))->find();
            $gc_info1 = db('goodsclass')->where('gc_id', $gc_info2['gc_parent_id'])->find();
            $insert_array = array();
            $insert_array['title'] = input('post.title');
            $insert_array['img'] = input('post.pic');
            $insert_array['type'] = input('post.type');
            $insert_array['brand_name'] = input('post.b_name');
            $insert_array['gc_name'] = input('post.type');
            $insert_array['status'] = intval(input('post.status'));
            $insert_array['brand_id'] = intval(input('post.b_id'));
            if (intval(input('post.cat_id2'))) {
                $insert_array['cat_id'] = intval(input('post.cat_id2'));
            } else if (intval(input('post.cat_id1'))) {
                $insert_array['cat_id'] = intval(input('post.cat_id1'));
            } else {
                $insert_array['cat_id'] = intval(input('post.cat_id'));
            }

            $insert_array['cat_id1'] = intval(input('post.cat_id'));
            $insert_array['cat_id2'] = intval(input('post.cat_id1'));
            $insert_array['cat_id3'] = intval(input('post.cat_id2'));
            $insert_array['gc_name'] = $gc_info1['gc_name'] . ',' . $gc_info2['gc_name'] . ',' . $gc_info3['gc_name'];
            $insert_array['content'] = trim(input('post.content'));
            $insert_array['add_time'] = time();
            $result = db('course')->insertGetId($insert_array);
            if ($result) {

                /* $upload_file = BASE_UPLOAD_PATH . DS . ATTACH_COMMON;
                   if (!empty($_FILES['img']['name'])) {//上传图片
                       $file = request()->file('img');
                       $file->validate(['ext' => ALLOW_IMG_EXT])->move($upload_file, 'course-img-' . $result . '.jpg');
                   }*/
                $this->log(lang('ds_add') . lang('ds_course') . '[' . input('post.title') . ']', 1);
                return json(['url' => url('Course/index'), 'code' => 1, 'msg' => '添加成功']);
            } else {
                $this->log(lang('ds_add') . lang('ds_course') . '[' . input('post.title') . ']', 0);
                return json(['url' => url('Course/index'), 'code' => 0, 'msg' => '添加失败']);
            }
        }
    }

    /**
     * 子教程添加
     */

    public function course_son_add()
    {
        if (empty(input('course_id'))) {
            $this->error('操作失败');
        }
        $goodsclass_model = model('goodsclass');
        if (!request()->isPost()) {
            $this->assign('course_id', input('course_id'));
            $this->setAdminCurItem('course_son_add');
            return $this->fetch('course_son_add');
        } else {
            //p(input('post.'));die;
            $insert_array = array();
            if (!empty(input('pic'))) {
                $insert_array['video'] = input('pic');
            }
            // 判断标题是否重复
            $course_info_unique = db('course_info')->where('title', '=', input('post.title'))->find();
            if ($course_info_unique) {
                return $this->error('已存在该教程名称');
            }
            $insert_array['title'] = input('post.title');
            $insert_array['x_id'] = intval(input('post.x_id'));
            $insert_array['qu'] = intval(input('post.qu'));
            $insert_array['status'] = intval(input('post.status'));
            $insert_array['content'] = input('post.content');
            $insert_array['add_time'] = time();
            $insert_array['course_id'] = intval(input('post.course_id'));
            $result = db('course_info')->insertGetId($insert_array);
            if ($result) {
                $this->log(lang('ds_add') . lang('ds_course') . '[' . input('post.title') . ']', 1);
                return json(['url' => url('Course/course_son_list', ['course_id' => $insert_array['course_id']]), 'code' => 1, 'msg' => '添加成功']);
            } else {
                $this->log(lang('ds_add') . lang('ds_course') . '[' . input('post.title') . ']', 0);
                return json(['url' => url('Course/course_son_list', ['course_id' => $insert_array['course_id']]), 'code' => 0, 'msg' => '添加失败']);
            }
        }
    }

    /**
     * 主教程编辑
     */
    public function course_edit()
    {
        $goodsclass_model = model('goodsclass');
        if (!request()->isPost()) {
            $course_id = input('get.course_id');
            $course_info = DB::name('course')->where(['id' => $course_id])->find();
            $this->assign('course_info', $course_info);
            #获取品牌
            $brand = DB::name('brand')->select();
            $this->assign('brand_list', $brand);
            //父类列表，只取到第二级
            $parent_list = $goodsclass_model->getTreeClassList(2);
            $gc_list = array();
            if (is_array($parent_list)) {
                foreach ($parent_list as $k => $v) {
                    $parent_list[$k]['gc_name'] = str_repeat("&nbsp;", $v['deep'] * 2) . $v['gc_name'];
                    if ($v['deep'] == 1)
                        $gc_list[$k] = $v;
                }
            }
            $this->assign('gc_list', $gc_list);
            //类型列表
            $type_model = model('type');
            $type_list = $type_model->getTypeList(array(), '', 'type_id,type_name,class_id,class_name');
            $t_list = array();
            if (is_array($type_list) && !empty($type_list)) {
                foreach ($type_list as $k => $val) {
                    $t_list[$val['class_id']]['type'][$k] = $val;
                    $t_list[$val['class_id']]['name'] = $val['class_name'] == '' ? lang('ds_default') : $val['class_name'];
                }
            }

            ksort($t_list);

            $this->assign('type_list', $t_list);
            $this->assign('gc_parent_id', input('get.gc_parent_id'));
            $this->assign('parent_list', $parent_list);
            #七牛云域名
            $file_http = db('config')->where('code', 'qiniu_http')->find();
            $url = $file_http['value'] . '/' . $course_info['img'];
            $this->assign('url', $url);
            // 品牌
            $brand_list = model('brand')->getBrandPassedList(array());
            $this->assign('brand_list', $brand_list);

            $this->setAdminCurItem('index');
            return $this->fetch('course_edit');
        } else {
            $insert_array = array();
            if (!empty(input('pic'))) {
                $insert_array['img'] = input('pic');
            }

            $course_id = input('post.course_id');

            $old_course_info = db('course')->where('id', $course_id)->find();
            $insert_array['title'] = input('post.title');
            $insert_array['status'] = intval(input('post.status'));
            $insert_array['brand_id'] = intval(input('post.b_id'));
            $insert_array['brand_name'] = input('post.b_name');
            $insert_array['type'] = intval(input('post.type'));

            $gc_ids = input('gc_ids');
            if (!isset($gc_ids) || $gc_ids != 1) {
                if (intval(input('post.cat_id2'))) {
                    $insert_array['cat_id'] = intval(input('post.cat_id2'));
                } else if (intval(input('post.cat_id1'))) {
                    $insert_array['cat_id'] = intval(input('post.cat_id1'));
                } else {
                    $insert_array['cat_id'] = intval(input('post.cat_id'));
                }

                $insert_array['cat_id1'] = intval(input('post.cat_id'));
                $insert_array['cat_id2'] = intval(input('post.cat_id1'));
                $insert_array['cat_id3'] = intval(input('post.cat_id2'));
                $gc_info3 = db('goodsclass')->where('gc_id', input('post.cat_id2'))->find();
                $gc_info2 = db('goodsclass')->where('gc_id', input('post.cat_id1'))->find();
                $gc_info1 = db('goodsclass')->where('gc_id', $gc_info2['gc_parent_id'])->find();
                $insert_array['gc_name'] = $gc_info1['gc_name'] . ',' . $gc_info2['gc_name'] . ',' . $gc_info3['gc_name'];
            }
            $insert_array['content'] = trim(input('post.content'));
            $insert_array['popular'] = input('post.popular');
            $result = db('course')->data($insert_array)->where(['id' => $course_id])->update();
            if ($result) {
                #更新教程信息
                if ($insert_array['status'] == 0) {
                    #更新子教程状态 更新商品教程
                    $son_course_info = db('course_info')->where('course_id', $course_id)->where('status', '1')->where('is_del', '0')->field('id')->select();
                    if (!empty($son_course_info)) {
                        db('course_info')->where('course_id', $course_id)->data(['status' => '0'])->update();
                    }

                    $goods_info = db('goods')->where('course_id', $course_id)->field('goods_id')->select();
                    if (!empty($goods_info)) {
                        db('goods')->where('course_id', $course_id)->data(['course_id' => '', 'course_name' => ''])->update();
                    }
                } else {
                    #更新商品教程
                    $goods_info = db('goods')->where('course_id', $course_id)->field('goods_id')->select();
                    if (!empty($goods_info)) {
                        if ($old_course_info['title'] != $insert_array['title']) {
                            db('goods')->where('course_id', $course_id)->data(['course_name' => $insert_array['title']])->update();
                        }
                    }
                }



                $this->log(lang('ds_edit') . lang('ds_course') . '[' . input('post.title') . ']', 1);
                return json(['url' => url('Course/index'), 'code' => 1, 'msg' => '编辑成功']);
            } else {
                $this->log(lang('ds_edit') . lang('ds_course') . '[' . input('post.title') . ']', 0);
                return json(['url' => url('Course/index'), 'code' => 1, 'msg' => '编辑失败']);
            }
        }
    }


    /**
     * 子教程编辑
     */
    public function course_son_edit()
    {
        if (!request()->isPost()) {
            #七牛云域名
            $file_http = db('config')->where('code', 'qiniu_http')->find();
            $this->assign('http_name', $file_http['value']);
            $course_id = input('get.course_id');
            $course_info = DB::name('course_info')->where(['id' => $course_id])->find();
            $this->assign('course_info', $course_info);
            $this->setAdminCurItem('course_son_edit');
            return $this->fetch('course_son_edit');
        } else {
            $insert_array = array();
            if (!empty(input('post.pic'))) {
                $insert_array['video'] = input('post.pic');
            }
            $course_id = input('post.course_id');
            $insert_array['title'] = input('post.title');
            $insert_array['status'] = intval(input('post.status'));
            $insert_array['x_id'] = intval(input('post.x_id'));
            $content = input('post.content');
            if (isset($content)) {
                $insert_array['content'] = trim($content);
            }
            $result = db('course_info')->data($insert_array)->where(['id' => $course_id])->update();
            $course_info = DB::name('course_info')->where(['id' => $course_id])->find();

            if ($result) {

                $this->log(lang('ds_edit') . lang('ds_course') . '[' . input('post.title') . ']', 1);
                return json(['url' => url('Course/course_son_list', ['course_id' => $course_info['course_id']]), 'code' => 1, 'msg' => '编辑成功']);
            } else {
                $this->log(lang('ds_edit') . lang('ds_course') . '[' . input('post.title') . ']', 0);
                return json(['url' => url('Course/course_son_list', ['course_id' => $course_info['course_id']]), 'code' => 0, 'msg' => '编辑失败']);
            }
        }
    }


    /**
     * 删除主教程
     */
    public function goods_class_del()
    {
        $course_id = input('param.course_id');
        $course_son_info = Db::name('course_info')->where(['course_id' => $course_id])->where('is_del', '<>', 1)->select();
        if (!empty($course_son_info)) {
            ds_json_encode('10001', lang('ds_son_no_del'));
        }
        $result = db('course')->where(['id' => $course_id])->data(['is_del' => 1, 'del_time' => time()])->update();

        #删除子教程状态 更新商品教程
        $son_course_info = db('course_info')->where('course_id', $course_id)->where('is_del', '0')->field('id')->select();
        if (!empty($son_course_info)) {
            db('course_info')->where('course_id', $course_id)->data(['is_del' => 1, 'del_time' => time()])->update();
        }

        $goods_info = db('goods')->where('course_id', $course_id)->field('goods_id')->select();
        if (!empty($goods_info)) {
            db('goods')->where('course_id', $course_id)->data(['course_id' => '', 'course_name' => ''])->update();
        }




        if ($result) {
            $this->log(lang('ds_del') . 'tag[ID:' . $course_id . ']', 1);
            ds_json_encode('10000', lang('ds_del_suc'));
        } else {
            $this->log(lang('ds_del') . 'tag[ID:' . $course_id . ']', 0);
            ds_json_encode('10001', lang('ds_del_ero'));
        }
    }

    /**
     * 删除子教程
     */
    public function course_son_del()
    {
        $course_id = input('param.course_id');
        $result = db('course_info')->where(['id' => $course_id])->data(['is_del' => 1, 'del_time' => time()])->update();
        if ($result) {
            $this->log(lang('ds_del') . 'tag[子ID:' . $course_id . ']', 1);
            ds_json_encode('10000', lang('ds_del_suc'));
        } else {
            $this->log(lang('ds_del') . 'tag[子ID:' . $course_id . ']', 0);
            ds_json_encode('10001', lang('ds_del_ero'));
        }
    }

    /*
     ajax 上传图片

    */
    public function ajax_upload()
    {
        $file_type = array('0' => 'image/jpeg', '1' => 'image/jpg', '2' => 'image/png');
        if (in_array($_FILES['file']['type'], $file_type)) {
            $file_name = input('post.name');
            $upload_info = upload_qiniu('file');
            return $upload_info;
        } else {
            return $data['msg'] = 0;
        }
    }


    #上传视频
    public function ajax_videos()
    {
        $old_name = $_FILES['file']['name'];
        $file_type = array('0' => 'mov', '1' => 'mp4', '2' => 'wmv', '3' => 'avi');
        $file_foot_name = substr($_FILES['file']['name'], (strripos($_FILES['file']['name'], ".")) + 1);
        if (!in_array($file_foot_name, $file_type)) {
            $data['err'] = 1;
            return $data;
        }
        $upload_info = upload_qiniu('file');
        $data['err'] = 0;
        $data['files_name'] = $upload_info['data'];
        $data['msg'] = '上传成功';
        return $data;
    }


    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'index',
                'text' => '主教程列表',
                'url' => url('Course/index')
            ),
            array(
                'name' => 'course_add',
                'text' => '主教程添加',
                'url' => url('Course/course_add')
            )
        );
        if (request()->action() === 'course_son_list' || request()->action() === 'course_son_add') {
            $menu_array = array(
                array(
                    'name' => 'index',
                    'text' => '主教程列表',
                    'url' => url('Course/index')
                ),
                array(
                    'name' => 'course_son_list',
                    'text' => '子教程列表',
                    'url' => url('Course/course_son_list', ['course_id' => $_GET['course_id']])
                ),
                array(
                    'name' => 'course_son_add',
                    'text' => '子教程添加',
                    'url' => url('Course/course_son_add', ['course_id' => $_GET['course_id']])
                ),
            );
        }
        if (request()->action() === 'course_son_edit') {
            $menu_array = array(
                array(
                    'name' => 'index',
                    'text' => '主教程列表',
                    'url' => url('Course/index')
                ),
                array(
                    'name' => 'course_son_edit',
                    'text' => '子教程编辑',
                    'url' => url('Course/course_son_edit', ['course_id' => $_GET['course_id']])
                ),
            );
        }

        return $menu_array;
    }
}
